package com.youchuang.listener;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

public class IndexListener implements ServletContextListener {
	private Logger logger = Logger.getLogger(IndexListener.class.getSimpleName());

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		Integer count = 0;
		ServletContext sc = sce.getServletContext();
		try {
			Scanner in = new Scanner(new FileReader("D:\\Backup\\Count\\count.txt"));
			// 读取已经产生的人数信息，然后进行累加
			count = in.nextInt();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			logger.error(e);
		}
		sc.setAttribute("AccessCount", count);
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		ServletContext sc = sce.getServletContext();
		Integer count = (Integer) sc.getAttribute("AccessCount");
		try {
			PrintWriter out = new PrintWriter(new FileWriter("D:\\Backup\\Count\\count.txt"));// 将人数保存到文本文件
			out.print(count);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e);
		}
	}

}
